<?php
/**
 * 后台管理控制器
 */
define('PAGESIZE', 20);

class Admin extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
    }
    
    public function index() {
       $this->isLogin();
       $this->load->view('/admin/index');      
    }
    
    /**
     * 判断用户是否已登录
     * @param $ajax 是否是ajax请求
     */
    private function isLogin($ajax = false) {
        if(!$this->session->userdata('username')) {
            if($ajax) {
                exit(json_encode(array('status'=>false,'info'=>'Verify Failed')));
            }
            redirect("c=admin&m=showLogin");
        }
    }
    
    /**
     * 登录页面
     */
    public function showLogin() {
        $this->load->view('/admin/login');
    }
    
    /**
     * 用户登录
     */
    public function doLogin() {
        $username = $this->input->post('username', TRUE);
        $password = $this->input->post('password', TRUE);
        
        if($username == '' || empty($username)) {
            exit(json_encode(array('status'=>FALSE, 'info'=>'请输入用户名')));
        }
        
        if($password == '' || empty($password)) {
            exit(json_encode(array('status'=>FALSE, 'info'=>'请输入密码')));
        }
        
        $this->load->model('user');
        $condition = array('username'=>$username,'password'=>md5($password));
        $result    = $this->user->getUser($condition,0,1,TRUE);
        
        if($result) {
            $sess = array('uid'=>$result['uid'], 'username'=>$username);
            $this->session->set_userdata($sess);
            exit(json_encode(array('status'=>TRUE, 'info'=>'登录成功，页面跳转中')));
        }
        
        exit(json_encode(array('status'=>FALSE, 'info'=>'登录失败')));
    }
    
    /**
     * 用户退出
     */
    public function doLogout() {
        $this->session->sess_destroy();
        redirect('c=admin');
    }
    
    /**
     * 显示用户列表
     */
    public function showUser() {
        $this->isLogin();
        $this->load->model('user');
        
        $data['user'] = $this->user->getUser(array(), 0, 15, FALSE);
        $data['loginUid'] = $this->session->userdata('uid');
        
        $this->load->view('/admin/common/header');
        $this->load->view('/admin/user',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 添加用户
     */
    public function addUser() {
        $this->isLogin(TRUE);
        
        $username = $this->input->post('username', TRUE);
        $password = $this->input->post('password', TRUE);
        
        if($username == '' || !$username) {
            exit(json_encode(array('status'=>FALSE,'info'=>'添加失败，用户名不能为空')));
        }
        
        if($password == '' || !$password) {
            exit(json_encode(array('status'=>FALSE,'info'=>'添加失败，密码不能为空')));
        }
        
        $this->load->model('user');
        
        //判断用户名是否已存在
        $condition = array('username'=>$username);
        $is_exist = $this->user->getUser($condition,0,1,TRUE);
        
        if(!empty($is_exist)) {
            exit(json_encode(array('status'=>FALSE,'info'=>'添加失败，用户名已存在')));
        }
        
        $res = $this->user->addUser($username, $password);
        
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'添加成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'添加失败')));
        }
    }

    /**
     * 删除用户
     */
    public function delUser() {
        $this->isLogin(TRUE);
        
        $uid = $this->input->post('uid', TRUE);
        
        if(!$uid) {
             exit(json_encode(array('status'=>FALSE,'info'=>'删除失败，请确认用户是否存在')));
        }

        $this->load->model('user');
        
        //用户ID是否存在
        $condition = array('uid'=>$uid);
        $is_exist = $this->user->getUser($condition,0,1,TRUE);
        
        if($this->session->userdata('username') != 'admin') {
            exit(json_encode(array('status'=>FALSE,'info'=>'删除失败，无权限')));
        }
        
        if($is_exist['username'] == 'admin') {
            exit(json_encode(array('status'=>FALSE,'info'=>'删除失败，无法删除超级用户')));
        }
        
        if($is_exist['username'] == $this->session->userdata('username')) {
            exit(json_encode(array('status'=>FALSE,'info'=>'删除失败，待删除用户为登录用户')));
        }
        
        if(empty($is_exist)) {
            exit(json_encode(array('status'=>FALSE,'info'=>'删除失败，请确认用户是否存在')));
        }
        
        $res = $this->user->delUser($uid);
        
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'删除成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'删除失败')));
        }
    }
    
    /**
     * 更新用户
     */
    public function updateUser() {
        $this->isLogin(TRUE);
        
        $uid = $this->input->post('uid',TRUE);
        $password = $this->input->post('password',TRUE);
        
        if($uid == '' || !$uid) {
            exit(json_encode(array('status'=>FALSE,'info'=>'网络错误，更新失败')));
        }
        
        if($password == '' || !$password) {
            exit(json_encode(array('status'=>FALSE,'info'=>'更新失败，密码不能为空')));
        }
        
        $this->load->model('user');
        
        //判断是否为登录用户
        if($uid != $this->session->userdata('uid')) {
            exit(json_encode(array('status'=>FALSE,'info'=>'更新失败，不能更新其他用户密码')));
        }
        
        //判断用户名是否存在
        $condition = array('uid'=>$uid);
        $is_exist = $this->user->getUser($condition,0,1,TRUE);
        
        if(empty($is_exist)) {
            exit(json_encode(array('status'=>FALSE,'info'=>'更新失败，用户不存在')));
        }
        
        $data = array('password'=>md5($password));                
        $res = $this->user->updateUser($uid, $data);
        
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'更新成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'更新失败')));
        }
    }
    
    /**
     * 显示站点信息
     */
    public function showInfo() {
        $this->isLogin();
        
        $data = array(
                        'HTTP_HOST' => $_SERVER['HTTP_HOST'],
                        'SERVER_SOFTWARE' => $_SERVER['SERVER_SOFTWARE'],
                        'MYSQL_VERSION' => mysql_get_server_info(),
                        'SERVER_PORT' => $_SERVER['SERVER_PORT'],
                        'IP' => $this->input->ip_address(),
                        'USER' => $this->session->userdata('username'),
                    );
        
        $this->load->view('/admin/common/header');
        $this->load->view('/admin/info',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 设置站点信息
     */
    public function showSite() {
        $this->isLogin();
        
        $data = parent::getSiteValue();
        
        $this->load->view('/admin/common/header');
        $this->load->view('/admin/site',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 更新站点信息
     */
    public function updateSite() {
        $this->isLogin(TRUE);
        
        $arr = array(
                        'copyright' => $this->input->post('copyright',TRUE),
                        'address' => $this->input->post('address',TRUE),
                        'zipcode' => $this->input->post('zipcode',TRUE),
                        'tel' => $this->input->post('tel',TRUE),
                        'fax' => $this->input->post('fax',TRUE),
                        'email' => $this->input->post('email',TRUE)
                    );
        
        if(!empty($arr)) {
            $this->load->model('site');
            $res = $this->site->setValue($arr);
            if($res) {
                exit(json_encode(array('status'=>true,'info'=>'更新成功')));
            }
        }
        
        exit(json_encode(array('status'=>false,'info'=>'更新失败')));
    }
    
    /**
     * 显示分类
     */
    public function showCategory() {
        $this->isLogin();
        
        $this->load->model('category');
        
        $data['category'] = $this->category->getCategory(array(), 0, 15, FALSE);
        
        $this->load->view('/admin/common/header');
        $this->load->view('/admin/category',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 添加分类
     */
    public function addCategory() {
        $this->isLogin(TRUE);
        
        $cname = $this->input->post('cname',TRUE);
        $order = $this->input->post('order',TRUE);
        
        if($cname == "" || $cname == NULL || empty($cname)) {
            exit(json_encode(array('status'=>false,'info'=>'请输入类目名称')));
        }
        
        if($order == "" || $order == NULL || empty($order)) {
            exit(json_encode(array('status'=>false,'info'=>'请输入类目排序')));
        }
        
        $this->load->model('category');
        
        //检查类目名称是否已经存在
        $condition = array('cname'=>$cname);
        $is_exist  = $this->category->getCategory($condition,0,1,TRUE);
        
        if(!empty($is_exist)) {
            exit(json_encode(array('status'=>false,'info'=>'类目名称已存在')));
        }
        
        //检查类目排序是否已经存在
        $condition = array('order'=>$order);
        $is_exist = $this->category->getCategory($condition,0,1,TRUE);
        
        if(!empty($is_exist)) {
            exit(json_encode(array('status'=>false,'info'=>'类目排序已存在')));
        }
        
        $res = $this->category->addCategory($cname, $order);
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'添加成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'添加失败')));
        }        
    }
    
    /**
     * 显示文章
     */
    public function showThread() {
        $this->isLogin();
        
        $page = $this->input->get('page',TRUE);
        $cid  = $this->input->get('cid',TRUE);        
        
        $this->load->model('category');
        $this->load->model('thread');
        
        $condition = array();
        if($cid) {
            $condition['cid'] = $cid;
        }
        
        //分页配置
        $count    = $this->thread->countAll();
        $max_page = (int)floor($count / PAGESIZE + 1);

        if(!isset($page) || !is_numeric($page)) {
            $page = 1;
        }
        
        if($page < 1) {
            $page = 1;
        }
        
        if($page >= $max_page) {
            $page = $max_page;
        }
        
        //分页输出
        $data['page']['count']   = $max_page;
        $data['page']['prev']    = ($page > 1) ? $page - 1 : 1;
        $data['page']['next']    = ($page < $max_page) ? $page + 1 : $max_page;
        $data['page']['current'] = $page;
        $offset = ($page-1)*PAGESIZE;
        
        $category       = $this->category->getCategory(array(),0,15,FALSE);
        $data['thread'] = $this->thread->getThread($condition,$offset,PAGESIZE,FALSE);
        $data['cid']    = $cid;

        if(!empty($category) && is_array($category)) {
            foreach($category as $key=>$value) {
                $data['category'][$value['cid']] = $value['cname'];
            } 
        }

        $this->load->view('/admin/common/header');
        $this->load->view('/admin/thread',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 显示添加文章
     */
    public function addThread() {
        $this->isLogin();
        
        $this->load->model('category');
        
        $data['category'] = $this->category->getCategory(array(),0,15,FALSE);
        $data['author'] = $this->session->userdata('username');
        
        $this->load->view('/admin/common/header');
        $this->load->view('/admin/addthread',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 添加文章
     */
    public function doThread() {
        $this->isLogin(TRUE);
        
        $this->load->model('category');
        $this->load->model('thread');
        
        $title = $this->input->post('title',TRUE);
        $cid = $this->input->post('cid',TRUE);
        $author = $this->input->post('author',TRUE);
        $link = $this->input->post('link',TRUE);
        $content = $this->input->post('content',TRUE);
        
        if($title == '' || empty($title)) {
            exit(json_encode(array('status'=>false,'info'=>'请输入文章标题')));
        }
        
        if($cid == '' || empty($cid)) {
            exit(json_encode(array('status'=>false,'info'=>'请选择文章所属类目')));
        }
        
        if($content == '' || empty($content)) {
            exit(json_encode(array('status'=>false,'info'=>'请输入文章内容')));
        }
        
        //判断类目是否存在
        $condition = array('cid'=>$cid);
        $is_exist  = $this->category->getCategory($condition,0,1,TRUE);
        if(empty($is_exist)) {
            exit(json_encode(array('status'=>false,'info'=>'所选文章类目不存在，请刷新后重试')));
        }
        
        $author = $author ?  $author : $this->session->userdata('username');
        $datetime = time();
        
        $res = $this->thread->addThread($title, $cid, $author, $content, $link, $datetime);
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'添加成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'添加失败')));
        }
    }

    /**
     * 删除文章
     */
    public function delThread() {
        $this->isLogin(TRUE);
        
        $tid = $this->input->post('tid',TRUE);
        
        $this->load->model('thread');
        
        //判断文章是否存在
        $condition = array('tid'=>$tid);
        $is_exist  = $this->thread->getThread($condition,0,1,TRUE);
        if(empty($is_exist)) {
            exit(json_encode(array('status'=>false,'info'=>'文章不存在，请刷新后重试')));
        }
        
        $res = $this->thread->delThread($tid);
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'删除成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'删除失败')));
        }
    }
    
    /**
     * 编辑文章
     */
    public function editThread() {
        $tid = $this->input->get('tid',TRUE);
        
        $this->load->model('thread');
        $this->load->model('category');
        
        $condition = array('tid'=>$tid);
        $is_exist  = $this->thread->getThread($condition,0,1,TRUE);
        if(empty($is_exist)) {
            show_404();
        }
        
        $data['thread'] = $this->thread->getThread(array('tid'=>$tid),0,1);
        $data['category'] = $this->category->getCategory(array(),0,15,FALSE);
        
        $this->load->view('/admin/common/header');
        $this->load->view('/admin/editthread',$data);
        $this->load->view('/admin/common/footer');
    }
    
    /**
     * 更新文章
     */
    public function updateThread() {
        $this->isLogin(TRUE);
        
        $this->load->model('category');
        $this->load->model('thread');
        
        $tid = $this->input->post('tid',TRUE);
        $title = $this->input->post('title',TRUE);
        $cid = $this->input->post('cid',TRUE);
        $author = $this->input->post('author',TRUE);
        $link = $this->input->post('link',TRUE);
        $content = $this->input->post('content',TRUE);
        $datetime = $this->input->post('datetime',TRUE);
        
        if($title == '' || empty($title)) {
            exit(json_encode(array('status'=>false,'info'=>'请输入文章标题')));
        }
        
        if($cid == '' || empty($cid)) {
            exit(json_encode(array('status'=>false,'info'=>'请选择文章所属类目')));
        }
        
        if($content == '' || empty($content)) {
            exit(json_encode(array('status'=>false,'info'=>'请输入文章内容')));
        }
        
        //判断文章是否存在
        $condition = array('tid'=>$tid);
        $is_exist  = $this->category->getThread($condition,0,1,TRUE);
        if(empty($is_exist)) {
            exit(json_encode(array('status'=>false,'info'=>'所选文章不存在，请刷新后重试')));
        }
        
        //判断类目是否存在
        $condition = array('cid'=>$cid);
        $is_exist  = $this->category->getCategory($condition,0,1,TRUE);
        if(empty($is_exist)) {
            exit(json_encode(array('status'=>false,'info'=>'所选文章类目不存在，请刷新后重试')));
        }
        
        $author = $author ?  $author : $this->session->userdata('username');
        $datetime = $datetime ? strtotime($datetime) : time();
        
        $data['title'] = $title;
        $data['datetime'] = $datetime;
        $data['author'] = $author;
        $data['content'] = $content;
        $data['link'] = $link;
        $data['cid'] = $cid;
        
        $res = $this->thread->updateThread($tid,$data);
        if($res) {
            exit(json_encode(array('status'=>TRUE,'info'=>'修改成功')));
        } else {
            exit(json_encode(array('status'=>FALSE,'info'=>'修改失败')));
        }        
    }
}
